package com.quyeying.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.quyeying.entity.TblUserEntity;
import com.quyeying.enums.SysConfigConstant;
import com.quyeying.mapper.TblUserDao;
import com.quyeying.service.TblUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quyeying.utils.RedisUtil;
import com.quyeying.utils.httputils.HttpUtil;
import com.quyeying.utils.result.ResultEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.quyeying.utils.result.R;
import com.quyeying.utils.result.ReturnPageData;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
* <p>
 * 用户表 服务实现类
 * </p>
*
* @author skx
* @since 2022-07-15
*/
@Service
public class TblUserServiceImpl extends ServiceImpl<TblUserDao, TblUserEntity> implements TblUserService {

    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.appSecret}")
    private String appSecret;
    @Resource
    ObjectMapper objectMapper;
    @Resource
    RedisUtil redisUtil;

    @Override
    public R findListByPage(Integer page, Integer pageCount){
        IPage<TblUserEntity> wherePage = new Page<>(page, pageCount);
        TblUserEntity where = new TblUserEntity();
        IPage<TblUserEntity> iPage = baseMapper.selectPage(wherePage, Wrappers.query(where));
        return R.success(ReturnPageData.fillingData(iPage));
    }

    @Override
    public R add(TblUserEntity tblUserEntity){
        baseMapper.insert(tblUserEntity);
        return R.success();
    }

    @Override
    public R delete(Long id){
        baseMapper.deleteById(id);
        return R.success();
    }

    @Override
    public R updateData(TblUserEntity tblUserEntity){
        baseMapper.updateById(tblUserEntity);
        return R.success();
    }

    @Override
    public R findById(Long id){
        TblUserEntity tblUserEntity = baseMapper.selectById(id);
        return R.success(tblUserEntity);
    }

    @Override
    public R wxLogin(String code) throws JsonProcessingException {
        //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid
                +"&secret="+appSecret+"&js_code="+code+"&grant_type=authorization_code";
        String result = HttpUtil.sendGetHttps(url, null);
        JsonNode jsonNode = objectMapper.readTree(result);

        if(!jsonNode.has("errcode")) {
            //根据登录用户得openid获取用户信息
            String openid = jsonNode.get("openid").asText();
            QueryWrapper<TblUserEntity> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("openid", openid);
            TblUserEntity userEntity = baseMapper.selectOne(userQueryWrapper);

            Map<String, Object> map = new HashMap<>(5);
            map.put("isNewUser", false);
            //保存用户信息
            TblUserEntity user = new TblUserEntity();
            if(!ObjectUtils.isEmpty(userEntity)) {
                user.setId(userEntity.getId());
                map.put("headImage", userEntity.getHeadImage());
                map.put("nickName", userEntity.getNickName());
            }else {
                user.setNickName(SysConfigConstant.SYS_PREFIX.concat(String.valueOf(System.currentTimeMillis()/1000)));
                user.setHeadImage(SysConfigConstant.SYS_USER_AVATAR_DEFAULT);
                map.put("nickName", user.getNickName());
                map.put("headImage", user.getHeadImage());
                map.put("isNewUser", true);
            }
            user.setOpenid(openid);
            saveOrUpdate(user);
            //缓存用户登录状态
            StringBuilder sb = new StringBuilder(openid.concat(String.valueOf(System.currentTimeMillis())));
            String token = DigestUtils.md5DigestAsHex(sb.toString().getBytes());
            redisUtil.set(token, user.getId(), 172800L);
            map.put("token", token);
            return R.success(map);
        }
        return R.error(ResultEnum.UNKNOWN_ERROR.getCode(), "登录失败");
    }

    public static void main(String[] args) {
        String s = UUID.randomUUID().toString().replaceAll("-", "");
        System.out.println(s);
    }
}
